package com.sample.thread.conf;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import lombok.Data;

/**
* @comments
* @author  zg
* @date 2021年3月13日
*/
@Data
@Component
public class ThreadPoolConfig {
    /** 线程池的名字 */
    public static final String THREAD_POOL_NAME = "Thread-Pool-1";
    
    private Integer corePoolSize = 10;//核心线程数

    private Integer maxPoolSize = 20;//最大线程数

    private Integer queueCapacity = 10;//队列大小
    
    private Integer keepAliveSeconds = 3600;//活跃时间
    
    private String threadNamePrefix = "test";//线程名字前缀
    
    /**
     * 如果queueCapacity满了，还有任务就会启动更多的线程，直到线程数达到maxPoolSize。如果超过此值，则根据拒绝策略进行处理。
     * 拒绝策略有多种：由任务调用线程执行,抛异常,多余的直接抛弃,根据FIFO（先进先出）抛弃队列里任务
     * @author zg
     * @date 2021-3-13 
     * @return
     */
    @Bean(name = THREAD_POOL_NAME)
    public Executor asyncServiceThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);//线程池核心线程，正常情况下开启的线程数
        executor.setQueueCapacity(queueCapacity);//线程队列容量。当核心线程数都被占用，多余的任务会存到此处
        executor.setMaxPoolSize(maxPoolSize);
        executor.setKeepAliveSeconds(keepAliveSeconds);//设置线程活跃时间（线程池中空闲线程等待工作的超时时间）
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());// 设置拒绝策略
        executor.initialize();
        return executor;
    }
}
